const app = getApp();
Page({
    data: {
        nowTem:'',//当前空调温度 取值为18到41
        temSpotId:'',
        temSpotItemId:'',
        roomTem:28,//室内温度 取值为-50到50
        modeNum:'',
        modeList:[], // 对应 bisSpotDto.spotCode
        isOpen:'',//当前设备是否开启 0 关闭 1 开启
        switchValue:{
            spotId:'',
            spotItemId:[63,64]
        },
        deviceId:'',//当前设备Id
        //图标库
        baseIco:[{
            "beibosi-wufoggy":"66f",
            "beibosi-8":"645",
            "beibosi-caozuoshibai":"6d2",
            "beibosi-qing":"635",
            "beibosi-duoyun":"673",
            "beibosi-wumai":"636",
            "beibosi-baoxue":"637",
            "beibosi-qiangshachenbao":"638",
            "beibosi-bingdongyuxue":"641",
            "beibosi-qingzhuanduoyun":"6e2",
            "beibosi-baoyu":"663",
            "beibosi-icon-test":"63e",
            "beibosi-yujiaxue":"633",
            "beibosi-jian":"639",
            "beibosi-xinxinicon":"678",
            "beibosi-_icon":"640",
            "beibosi-kongtiao-chushi":"63d",
            "beibosi-leizhenyubanbingbao":"646",
            "beibosi-icon-test1":"63f",
            "beibosi-tianqiku-fanganyi-duoyunzhuanqingtian":"713",
            "beibosi-tianqiku-fanganyi-longjuanfeng":"71f",
            "beibosi-shuaxin":"769",
            "beibosi-icontubiao":"6c1",
            "beibosi-zanwushuju":"63a",
            "beibosi-fengsu-gao":"6f0",
            "beibosi-shuaxin1":"63b",
            "beibosi-mini-bangzhux":"600",
            "beibosi-min-guanbix":"601",
            "beibosi-min-shezhix":"602",
            "beibosi-gongneng-shaixuanx":"603",
            "beibosi-jiaju-dianshix":"604",
            "beibosi-jiaju-jiankongx":"605",
            "beibosi-jiaju-kongtiaox":"606",
            "beibosi-jiaju-saodijix":"607",
            "beibosi-jiaju-touyingx":"608",
            "beibosi-kongtiao-fengsux":"609",
            "beibosi-kongtiao-fengxiangx":"60a",
            "beibosi-kongtiao-furex":"60b",
            "beibosi-kongtiao-qiehuanmoshix":"60c",
            "beibosi-kongtiao-zhilengx":"60d",
            "beibosi-liebiao-kaiguanx":"60e",
            "beibosi-liebiao-tiaojiex":"60f",
            "beibosi-liebiao-tiaojiefangxiangx":"610",
            "beibosi-moshi-dingshix":"611",
            "beibosi-moshi-jienengx":"612",
            "beibosi-moshi-likaix":"613",
            "beibosi-moshi-zhinengx":"614",
            "beibosi-shezhi-anquanrizhix":"615",
            "beibosi-shezhi-wodeshouquanx":"616",
            "beibosi-shezhi-xunitiyanx":"617",
            "beibosi-shoujihaox":"618",
            "beibosi-shouye-changyongweixuanzhongx":"619",
            "beibosi-shouye-ketingxuanzhongx":"61a",
            "beibosi-shouye-woshixuanzhongx":"61b",
            "beibosi-tishi-tongguox":"61c",
            "beibosi-yinle-bofangzhongx":"61e",
            "beibosi-yinle-shanchux":"61f",
            "beibosi-yinle-shanchuquanbux":"620",
            "beibosi-yinle-suijibofangx":"621",
            "beibosi-yinle-xunhuanzhongx":"622",
            "beibosi-icon-shidux":"61d",
            "beibosi-icon-shuizhix":"623",
            "beibosi-icon-xiaoxix":"624",
            "beibosi-icon-youjiantoux":"625",
            "beibosi-icon-xuanzhongx":"627",
            "beibosi-chuanglian-dakaix":"628",
            "beibosi-menjin-dakaix":"629",
            "beibosi-min-guanbichuanglianx":"62a",
            "beibosi-icon-zuojiantoux1":"62b",
            "beibosi-chuanglian-tingzhiguanbix":"626",
            "beibosi-menjin-guanbix":"62c",
            "beibosi-yinle-liebiaox":"62d",
            "beibosi-yinle-shangyishoux":"62e",
            "beibosi-yinle-tingzhix":"62f",
            "beibosi-yinle-bofangx":"630",
            "beibosi-yinle-xiayishoux":"631",
            "beibosi-icon-fanhuix":"632",
            "beibosi-icon-youjiantoux-copy":"714",
            "beibosi-menjin-suox":"634",
            "beibosi-shebei-chuanglian-line":"63c"
        }],
    },
    tabModeFuc:function(){//切换模式
        var that = this;
        var modeNum = that.data.modeNum;
        var setValue = '';
        if(modeNum!==''){//判断modeNum是否为空 为空则为关闭状态 不执行
            if(modeNum<3){
                modeNum ++
            }else{
                modeNum = 0;
            }
            setValue = {
                modeNum:modeNum
            };
            var spotId = that.data.modeList[modeNum].spotId;
            var spotItemId = that.data.modeList[modeNum].spotItemId;
            console.log(spotId+'/'+spotItemId)
            that.globalChangeFuc(spotId,spotItemId,"",setValue);
        }

    },
    selModeFun:function(e){//选择模式
        var that=this;
        var index = e.currentTarget.dataset.index;
        var setValue ='';
        if (index != that.data.modeNum.toString()) {//判断当前是否为选择状态 否则执行
            setValue = {
                modeNum:index
            };
            var spotId = that.data.modeList[index].spotId;
            var spotItemId = that.data.modeList[index].spotItemId;
            that.globalChangeFuc(spotId,spotItemId,'',setValue);
        }
    },
    switchFuc:function () {//开关操作
        var that = this;
        var isOpen = that.data.isOpen;//获取当前开关状态
        var spotId = that.data.switchValue.spotId;
        var spotItemId ='';
        var setValue = '';
        if (isOpen == "0"){//判断关闭开启
            isOpen = "1";
            spotItemId = that.data.switchValue.spotItemId[1];
            setValue = {
                isOpen:isOpen,
            };
        }else{
            isOpen = "0";
            spotItemId = that.data.switchValue.spotItemId[0];
            setValue = {
                isOpen:isOpen,
                modeNum:'',  //如果操作关闭成功时 关闭所有模式
                nowTem:'' //如果操作关闭成功时 关闭温度显示
            };
        }
        that.globalChangeFuc(spotId,spotItemId,'',setValue);

    },
    tempChangeFuc(e){//温度加减
        var that = this;
        var temVal = that.data.nowTem;
        var arith = e.currentTarget.dataset.arith;
        var spotId = that.data.temSpotId;
        var spotItemId = that.data.temSpotItemId;
        if(temVal!==''){
            if (arith>0 && temVal>40){
                temVal = 41;
            }else if (arith<0 && temVal<19){
                temVal = 18;
            }else{
                temVal = Number(temVal) + Number(arith);
            }
            var setValue ={
                nowTem:temVal,
            };
            that.globalChangeFuc(spotId,spotItemId,temVal,setValue);
        }
    },
    globalChangeFuc:function(spotId,spotItemId,temVal,setValue){//value为需要传入温度值或状态值是写入  setValue为传入需要设置公共字段的数据集合
        var that = this;
        var parame = '';
        if(temVal){//判断 设置请求参数
            parame = spotId+'/'+spotItemId+'?thermal='+temVal;
        }else{
            parame = spotId+'/'+spotItemId
        }
        // that.setData(setValue);
        wx.showLoading();//
        wx.request({
            url: app.globalData.globalApi+"home/operationEquipment/"+parame,//设备页面操作请求公共接口
            data:{
            },
            method: 'get', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType:'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function(res){
                console.log(res.data.data);

                that.setData(setValue);//调用接口成功时  执行传入设置数据函数
                if(that.data.isOpen=='1'){
                    that.loadDataFuc(that.data.deviceId);//重新载入空调数据
                }
                wx.hideLoading()
            }
        });
    },
    selectIco:function(id){//根据传入图标代码获取图标名
        var that = this;
        var num = "";//截取图标编码后三位
        var baseIco = that.data.baseIco[0];
        var thisIcoVal = "";
        var className = "";
        if (id){
            num = id.substring(id.length-4,id.length-1);
            for( let i in baseIco) {
                thisIcoVal = baseIco[i];
                if (thisIcoVal == num){//匹配到图标时跳出
                    className = i;
                    break;
                }
            }
        }
        return className;
    },
    //处理设备信息数据-组装逻辑部分
    filterDate:function(data){
        var that = this;
        console.log(data)
        //处理更新数据
        var isOpen ='';
        var modeNum ='';
        var lengthO = data.bisSpotDto.length;
        var lengthI = '';
        var spotTypeO ='';
        var spotValueI = '';
        var switchValue = '';
        var modeList = [];
        var nowTem ='';
        var temSpotId = '';
        var temSpotItemId = '';
        if(lengthO !== 0){//判断是否存在设备信息
            for(let i=0;i<lengthO;i++){//组装数据
                lengthI= data.bisSpotDto[i].bisSpotItems.length;
                spotTypeO = data.bisSpotDto[i].spotType;
                console.log(spotTypeO)

                if(spotTypeO == 'C1') {//初始化开关数据
                    isOpen = data.bisSpotDto[i].spotValue;
                    switchValue = {spotId:data.bisSpotDto[i].spotId, spotItemId:[]};
                    for(let f=0;f<lengthI;f++){
                        spotValueI = data.bisSpotDto[i].bisSpotItems[f].itemValue;
                        switchValue.spotItemId[spotValueI] = data.bisSpotDto[i].bisSpotItems[f].spotItemId;
                    }
                    that.setData({
                        isOpen:isOpen,
                        switchValue:switchValue
                    })
                }else if(spotTypeO == 'C2'){
                    modeNum = data.bisSpotDto[i].spotValue;
                    for(let f=0;f<lengthI;f++){
                        spotValueI = data.bisSpotDto[i].bisSpotItems[f].itemValue;
                        modeList[spotValueI] = {index:spotValueI,spotId:data.bisSpotDto[i].spotId,itemName:data.bisSpotDto[i].bisSpotItems[f].itemName,spotItemId:data.bisSpotDto[i].bisSpotItems[f].spotItemId,iconName:that.selectIco(data.bisSpotDto[i].bisSpotItems[f].itemIcon)};
                        console.log(modeList)
                    }
                    that.setData({
                        modeNum:modeNum,
                        modeList:modeList
                    })
                }else if(spotTypeO == 'C3'){
                    nowTem = data.bisSpotDto[i].spotValue;
                    temSpotId = data.bisSpotDto[i].spotId;
                    temSpotItemId = data.bisSpotDto[i].bisSpotItems[0].spotItemId;
                    console.log(temSpotItemId)
                    that.setData({
                        nowTem:nowTem,
                        temSpotId:temSpotId,
                        temSpotItemId:temSpotItemId
                    })
                }
            }
            //页面加载判断 开关关闭 取消所有模式 和温度
            if(that.data.isOpen == '0'){
                that.setData({
                    modeNum:'',
                    nowTem:''
                })
            }
        }

    },
    onLoad: function (options) {
        // 调用应用实例的方法获取全局数据
        let app = getApp();
        // toast组件实例
        new app.ToastPannel();
        // 页面初始化 options为页面跳转所带来的参数
        var that = this;
        var deviceId = options.deviceId;
        that.setData({
            deviceId:deviceId
        });
        that.loadDataFuc()//加载空调数据
     },
    loadDataFuc:function(){
        var that = this;
        var deviceId = that.data.deviceId;
        wx.request({
            url: app.globalData.globalApi+"home/quipmentDetail/"+deviceId,
            data:{
            },
            method: 'get', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType:'json',
            header: {
                "token-session": app.globalData.tokenSession, // 设置请求的header，写入返回token
                'experience-Pattern':app.globalData.experiencePattern// 是否为体验用户
            },
            success: function(res){
                var data = res.data.data;
                console.log(data);
                that.filterDate(data);//调用数据组装逻辑
            },
            fail:function () {
            }
        });
    },
    onReady: function () {
        var that = this;
        // 页面渲染完成

        //加载环形温度条
        var cxt_arc = wx.createCanvasContext('canvasArc');//创建并返回绘图上下文context对象。
        var maxTem = 50; //温度正负最大取值
        var basePoint = 1.5; //12点方向基准角度值
        var changPoint = 0.76; //预设角度最大偏移量
        var roomTem = that.data.roomTem;//获取当前温度值
        var point = basePoint+changPoint*(roomTem/maxTem);//计算当前角度
        // 遮罩
        cxt_arc.setLineWidth(12);
        cxt_arc.setStrokeStyle('#777');
        cxt_arc.setLineCap('butt');
        cxt_arc.beginPath();//开始一个新的路径
        cxt_arc.arc(106, 106, 81,point * Math.PI, (basePoint+changPoint) * Math.PI,false);
        cxt_arc.stroke();//对当前路径进行描边

        cxt_arc.setLineWidth(12);
        cxt_arc.setStrokeStyle('#777');
        cxt_arc.setLineCap('round');
        cxt_arc.beginPath();//开始一个新的路径
        cxt_arc.arc(106, 106, 81,2.2 * Math.PI, (basePoint+changPoint)  * Math.PI, false);//设置一个原点(106,106)，半径为100的圆的路径到当前路径
        cxt_arc.stroke();//对当前路径进行描边
        cxt_arc.draw();
        that.socketFuc();//连接websocket
    },
    onShow: function () {
        // 页面显示
        var that = this;
        // that.socketFuc();//连接websocket
    },
    onHide: function () {
        // 页面隐藏
        var that = this;
        that.data.task.close();//关闭当前页websocket
    },
    onUnload: function () {
        // 页面关闭
    },
    //websocket函数
    socketFuc:function() {
        var that = this;
        var socketTask = wx.connectSocket({
            url: app.globalData.socketUrl,
            success: function (res) {
                console.log(res)
            }
        });
        console.log(socketTask)
        that.setData({
            task: socketTask
        });
        // 监听链接成功
        socketTask.onOpen(function (res) {
            console.log(res);
            socketTask.send({
                data: app.globalData.tokenSession,
                success: res => {
                    console.log(res + '发送成功')
                },
                fail: err => {
                    console.log(err + '失败')
                }

            });
        });
        // 接收更新数据
        socketTask.onMessage(function (data) {
            var objData = JSON.parse(data.data);
            console.log(objData);


            var nowDeviceId = that.data.deviceId;//获取当前设备Id
            var clientData = objData.clientData;//获取更新数据列表
            var data_type = objData.data_type; //判断传入数据源类型  device_change时为设备变更
            if(data_type=='device_change'){//如果传入数据为更新设备
                var length = clientData.length;
                var deviceId = '';
                if(length!==0){//当前设备列表存在数据时候
                    for(let i=0;i<length;i++){
                        deviceId = clientData[i].deviceId;//获取设备id
                        if(deviceId == nowDeviceId){//匹配当前设备
                            that.filterDate(clientData[i])//调用数据组装逻辑
                        }
                    }
                }

            }else{//权限有变更 给出提示后跳转首页
                that.show('权限有变更','failed','','../controlIndex/controlIndex');//弹出提示信息
            }
        });
        //连接失败
        socketTask.onError(function () {
            console.log('websocket连接失败！');
        });
    },
    // backFuc:function(){//跳转操控首页
    //     console.log(333);
    //     wx.navigateTo({
    //         url: "../controlIndex/controlIndex",
    //     });
    // }
});
